// 199010120 唐梓铭
Vue.createApp({
  data() {
    return {
      readySubmit: false,
      // 省市区filter
      allCity: [],
      cities: [],
      towns: [],
      // form表单数据
      form: {
        username: "",
        password: "",
        repassword: "",
        phone: "",
        sex: "",
        province: "",
        city: "",
        town: "",
        date: "",
        idcard: "",
      },
    };
  },
  mounted() {
    // 获取省市区数据
    fetch("./data.json")
      .then((response) => {
        if (response.status === 200) {
          return response.json();
        }
      })
      .then((res) => {
        res.map((item) => {
          this.allCity.push(item);
        });
        console.log(this.allCity);
      });
  },
  methods: {
    changeProvince(e) {
      this.province = e.currentTarget.value;
      this.towns = "";
      this.cities = [
        ...this.allCity.filter((item) => item.name === e.currentTarget.value),
      ][0];
    },
    changeCity(e) {
      this.form.city = e.currentTarget.value;
      this.towns = [
        ...this.cities.city.filter(
          (item) => item.name == e.currentTarget.value
        ),
      ][0];
    },
    changeTown(e) {
      this.form.town = e.currentTarget.value;
    },
    // 提交按钮
    submit() {
      const res = this.validateAll();
      if (res) {
        alert("注册成功");
      }
    },
    // 验证所有
    validateAll() {
      const res =
        this.validateUsername() &&
        this.validateRepassword() &&
        this.validatePassword() &&
        this.validatePhone() &&
        this.validateIdcard();
      return res;
    },
    validateUsername() {
      const res = this.form.username.length ? true : false;
      if (res) {
        return true;
      } else {
        alert("用户名不能为空");
        return false;
      }
    },
    validatePhone() {
      const res = this.form.phone
        .toString()
        .match(/^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/)
        ? true
        : false;
      if (res) {
        return true;
      } else {
        alert("电话不合法");
        return false;
      }
    },
    validatePassword() {
      const res =
        this.form.password.length > 6 && this.form.password.length <= 20
          ? true
          : false;
      if (res) {
        return true;
      } else {
        alert("密码长度必须大于6位，不超过20位");
        return false;
      }
    },
    validateRepassword() {
      const res = this.form.password === this.form.repassword ? true : false;
      if (res) {
        return true;
      } else {
        alert("两次密码不一致");
        return false;
      }
    },
    validateIdcard() {
      const res = this.form.idcard.match(
        /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      );
      if (res) {
        return true;
      } else {
        alert("身份证不合法");
        return false;
      }
    },
  },
}).mount("#app");
